//
//  PingPlugin.m
//  BSLPlugin
//
//  Created by Foreveross BSL on 16/1/7.
//  Copyright © 2016年 Fanty. All rights reserved.
/*
API Key: GcnAOYUIg8IxGVtWdyOjYNC8
Secret Key: 9OZa1ap3i3eo5TsGVFpGFrrId0oGxeKu

**/

#import "BDTTSPlugin.h"

@interface BDTTSPlugin ()
@property (nonatomic,copy) NSString *isNowPlay;
@end
@implementation BDTTSPlugin

{
    NSString *_APIKey;
    NSString *_SecretKey;
}

- (void)getTextToSynthesizer:(CDVInvokedUrlCommand*)command{
    
    if (command.arguments.count<2) {
        UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"所传参数不够,请添加参数" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"知道了", nil];
        [alerView show];
        return;
    }
    
    self.textData = [NSMutableData dataWithCapacity:0];
    self.textArray = [NSMutableArray arrayWithCapacity:0];
    self.isNowPlay = [command.arguments lastObject];
    for (int i = 0; i<command.arguments.count-1; i++) {
        [self.textArray addObject:[command.arguments objectAtIndex:i]];
    }

    if (![_APIKey isEqualToString:@""]&&![_SecretKey isEqualToString:@""]) {
        _synthesizer = [[BDSSpeechSynthesizer alloc] initSynthesizerWithDelegate:self];
        [self.synthesizer setApiKey:_APIKey withSecretKey:_SecretKey];
        if ([self.isNowPlay isEqualToString:@"true"]) {
            //边合成边播放
            [self.synthesizer batchSpeak:self.textArray];
        }
        else{
            // 合成之后可选择再播放
            [self.synthesizer batchSynthesize:self.textArray];
        }
        
        [self.synthesizer setSynthesizerParam:[NSNumber numberWithInt:BDS_SYNTHESIZER_TEXT_ENCODE_UTF8]
                                       forKey:BDS_SYNTHESIZER_PARAM_TEXT_ENCODE
         ];
        [self.synthesizer setSynthesizerParam:[NSNumber numberWithInt:BDS_SYNTHESIZER_SPEAKER_FEMALE]
                                       forKey:BDS_SYNTHESIZER_PARAM_SPEAKER
         ];
        [self.synthesizer setSynthesizerParam:[NSNumber numberWithInt:5]
                                       forKey:BDS_SYNTHESIZER_PARAM_VOLUME
         ];
        [self.synthesizer setSynthesizerParam:[NSNumber numberWithInt:5]
                                       forKey:BDS_SYNTHESIZER_PARAM_SPEED
         ];
        [self.synthesizer setSynthesizerParam:[NSNumber numberWithInt:5]
                                       forKey:BDS_SYNTHESIZER_PARAM_PITCH
         ];
        [self.synthesizer setSynthesizerParam:[NSNumber numberWithInt:BDS_SYNTHESIZER_AUDIO_ENCODE_AMR_15K85]
                                       forKey:BDS_SYNTHESIZER_PARAM_AUDIO_ENCODING
         ];

    }
    else{
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"请确定是否填写APIKey,SecretKey"];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    }
    
  
  
}
// 合成之后可选择播放
- (void)PlayVoice:(CDVInvokedUrlCommand*)command{
    if (self.textData.length!=0 ) {
     _voicePath = [[self getDataPath] stringByAppendingPathComponent:@"analysisVoice.mp3"];
      [self.textData writeToFile:_voicePath atomically:YES];
    }
    _tempPlayer = [[BDSBuiltInPlayer alloc] init];
    _tempPlayer.delegate = self;
    NSError *arr = nil;
    _command = command;
    if ([[NSFileManager defaultManager]fileExistsAtPath:_voicePath]) {
       [_tempPlayer playContentsOfURL:[NSURL fileURLWithPath:_voicePath] error:&arr];
        if (arr) {
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[NSString stringWithFormat:@"%@",arr]];
            [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
        }
    }
    else{
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"没有缓存的语音文件"];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    }
}

# pragma  mark BDSSpeechSynthesizerDelegate
- (void)synthesizerNewDataArrived:(BDSSpeechSynthesizer *)speechSynthesizer data:(NSData *)newData DataFormat:(BDSAudioFormat)fmt characterCount:(int)newLength
 sentenceNumber:(NSInteger)SynthesizeSentence
{
   // NSLog(@"newLength = %d characters of sentence = %d   fmt= %u ", newLength, SynthesizeSentence,fmt);
    if (![self.isNowPlay isEqualToString:@"true"]) {
          [self.textData appendData:newData];
    }
 
}

# pragma mark BDSBuiltInPlayerDelegate
- (void)playerDidFinished:(BDSBuiltInPlayer *)player{
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"播放成功"];
    [self.commandDelegate sendPluginResult:result callbackId:_command.callbackId];
}
- (void)playerDidPaused:(BDSBuiltInPlayer *)player{
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"播放暂停，可能被其他程序中断"];
    [self.commandDelegate sendPluginResult:result callbackId:_command.callbackId];
}

- (void)playerErrorOccured:(BDSBuiltInPlayer *)player error:(NSError*)error{
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[NSString stringWithFormat:@"播放失败:%@",error]];
    [self.commandDelegate sendPluginResult:result callbackId:_command.callbackId];
}

- (NSString *)getDataPath{
    NSString *str =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/data"];
    NSFileManager *file = [NSFileManager defaultManager] ;
    
    if (![file fileExistsAtPath:str]) {
        [file createDirectoryAtPath:str withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return str;
}
- (void)pluginInitialize
{
    // 设置日志级别
    [BDSSpeechSynthesizer setLogLevel: BDS_PUBLIC_LOG_DEBUG];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"BDTTSConfig.plist" ofType:nil];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    _APIKey = [dict objectForKey:@"APIKey"];
    _SecretKey = [dict objectForKey:@"SecretKey"];
    if ([_APIKey isEqualToString:@"{APIKey}"]||[_SecretKey isEqualToString:@"{SecretKey}"]) {
        _APIKey = @"GcnAOYUIg8IxGVtWdyOjYNC8";
        _SecretKey = @"9OZa1ap3i3eo5TsGVFpGFrrId0oGxeKu";
    }
    [self getDataPath];
    NSLog(@"首先执行的代码");
}

@end
